var express = require('express');
var path = require("path");
let fs = require("fs");
let timer = require("time-stamp");
var router = express.Router();

/* GET home page. */
router.get('/', function(req, res, next) {
  res.render('index', { title: 'Express' });
});

// 登录
router.get("/login",(request,response) => {
  response.sendFile(path.resolve("./views/login.html"));
});

// 注册
router.get("/register",(request,response) => {
  response.sendFile(path.resolve("./views/register.html"));
});

// 登录验证
router.post("/dologin",(request,response,next) => {
  let {tel,pass} = request.body;
  let read = JSON.parse(fs.readFileSync("./mingdan.json").toString("utf-8"));
  let num = read.findIndex((a) => {
    return a.tel == tel && a.pass == pass;

  });
  if(num != -1){
    response.send("登录成功");
  }else{
    let num = read.findIndex((a) => {
      return a.tel == tel;
    });
    if(num == -1){
      next("账号错误");
    }else{
      next("密码错误");
    }
  }
  
})

// 注册验证
router.post("/doregister",(request,response,next) => {
  let {tel,pass} = request.body;
  let read = JSON.parse(fs.readFileSync("./mingdan.json").toString("utf-8"));
  let num = read.findIndex((a) => {
    return a.tel == tel;
  });
  if(num != -1){
    next("该账号已注册");
  }else{
    let time = timer("YYYY年MM月DD日 HH时mm分ss秒");
    read.push({tel,pass,time});
    fs.writeFileSync("./mingdan.json",JSON.stringify(read));
    response.send("注册成功");
  }
  
})


module.exports = router;
